<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function getIndex(){
        //查询所有数据
       $data = DB::table('user')->paginate(5);
        $title = '学生在线考试系统';
        return view('admin.table',['title'=>$title,'data'=>$data]);
    }
    //删除数据
    public function getDelete($id){
        $res = DB::table('user')->where('id','=',$id)->delete();
        if($res>0){
            return redirect('/user/index')->with('info','删除成功');
        }else{
            return back()->with('info','删除失败');
        }
    }
    //修改页面
    public function getEdit($id){
        $data = DB::table('user')->where('id','=',$id)->first();
        $title = '用户修改页面';
        return view('/admin.edit',['data'=>$data,'title'=>$title]);
    }
    //修改数据
    public function postUpdate($id,Request $request){
         $data = $request->except('_token');
       $res = DB::table('user')->where('id','=',$id)->update($data);
       if($res>0){
            return redirect('/user/index')->with('error','修改成功');
       }else{
            return back()->with('error','修改失败');
       }
    }
    //插入页面
    public function getAdd(){
        $title='这是插入页面';
        return view('/admin/insert',['title'=>$title]);
    }
    //添加数据
    public function postInsert(Request $request){

        $data = $request->only('username','password','age');

        if(empty($request->input('username'))){
            return back()->with('error','用户名不能为空');
        }
        if(!($data['password']==$request->Input('repassword'))){
            $request->flash();
            return back()->with('error','两次密码不一致');
        }
        // $data['password']= Hash::make($data['password']);
        //处理密码 使用hash加密
        $data['password'] = Hash::make($data['password']);
      
        $res = DB::table('user')->insert($data);
        
        if($res>0){
             return redirect('/user/index')->with('error','添加成功');
        }else{
            $request->flashOnly('age','sex');
            return back()->with('error','添加失败');
        }
    }
}
